package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Slf4j
@Component//一定要加载到ioc容器中
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override//过滤器逻辑
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求request
        ServerHttpRequest request = exchange.getRequest();

        //2.获取uri的path请求路径
        String path = request.getPath().toString();

        //2.1白名单
        List<String> excludePaths = authProperties.getExcludePaths();

        //判断当前请求路径是否是白名单,使用antPathMatcher进行匹配
        for (String excludePath : excludePaths) {
            boolean match = antPathMatcher.match(excludePath, path);
            if (match) {
                return chain.filter(exchange);
            }
        }

        //3.获取请求头中的token（authorization）
        String token = exchange.getRequest().getHeaders().getFirst("authorization");

        //3.1 //如果token为空则返回401错误
        if (token == null) {
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //4.如果token不为空则校验，并从中获取userId

        Long userId = null;

        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //验证失败,返回token无效的错误
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //将userId放入请求头
        request.mutate().header("user-info", userId.toString());

        //token有效，传递用户信息
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
